class MessageController < ApplicationController
  before_filter :protect
  layout 'user'
  
  def inbox
    @title = "收件箱"
    @messages = @login_user.rmessages.find(:all, :conditions => ["is_rdelete = ?", 0])
  end

  def outbox
    @title = "已发送"
    @messages = @login_user.smessages.find(:all, :conditions => ["is_sdelete = ?", 0])
  end
  
  def trashbox
    @title = "垃圾箱"
    @messages = @login_user.rmessages.find(:all, :conditions => ["is_rdelete = ?", 1]) + @login_user.smessages.find(:all, :conditions => ["is_sdelete = ?", 1])
  end

  def send_message
    @title = "发站内信"
    @username = params[:username]
    if param_posted?(:message)
      @message = Message.new(params[:message])
      @message.suser = @login_user
      if @message.save && @login_user.smessages<<@message
        redirect_to :action => "outbox"      
      end
    end
  end
  
  def show_message
    id = params[:id]
    @message = Message.find(id)
    @message.update_attribute(:is_read, 1) if @login_user==@message.ruser
  end
  
  def delete_inbox
    delete_message("inbox")
    redirect_to :action => :inbox
  end
  
  def delete_outbox
    delete_message("outbox")
    redirect_to :action => :outbox
  end
  
  def delete_trashbox
    delete_message("trashbox")
    redirect_to :action => :trashbox
  end
  

  
  private
  
  def delete_message(box)
    case box
      when "inbox"
        Message.update_all("is_rdelete=1", :id => params[:delete_ids])
      when "outbox"
        Message.update_all("is_sdelete=1", :id => params[:delete_ids])
      when "trashbox"
        Message.update_all("is_rdelete=2", {:id => params[:delete_ids], :receiver_id => @login_user.id})
        Message.update_all("is_sdelete=2", {:id => params[:delete_ids], :sender_id => @login_user.id})
    end
    
    
  end

end
